package cn.xiaoliu.hrm.service.impl;

import cn.xiaoliu.hrm.domain.LoginUser;
import cn.xiaoliu.hrm.domain.VipUser;
import cn.xiaoliu.hrm.dto.RegisterDto;
import cn.xiaoliu.hrm.feign.RegisterFeignClient;
import cn.xiaoliu.hrm.mapper.VipUserMapper;
import cn.xiaoliu.hrm.service.IVipUserService;
import cn.xiaoliu.hrm.util.AjaxResult;
import cn.xiaoliu.hrm.util.BitStatesUtils;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.validation.Valid;
import javax.validation.constraints.NotBlank;

/**
 * <p>
 * 会员登录账号 服务实现类
 * </p>
 *
 * @author xiaoliu
 * @since 2021-12-25
 */
@Service
public class VipUserServiceImpl extends ServiceImpl<VipUserMapper, VipUser> implements IVipUserService {
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private RegisterFeignClient registerFeignClient;
    @Autowired
    private VipUserMapper vipUserMapper;

    @Override
    public AjaxResult register(@Valid RegisterDto dto) {
        //校验验证码
        String smsCode = dto.getSmsCode();
        Object data = redisTemplate.opsForValue().get("REGISTE::" + dto.getMobile());
        if (data==null){
            throw new RuntimeException("验证码过期，请重新获取");
        }
        if (!smsCode.equals(data.toString())){
            throw new RuntimeException("验证码输入有误，请重新输入");
        }
        //后期要做权限，所有先要保存到auth服务中的T_login_user表返回主键id然后再保存到T_vip_user
        //保存T_login_user信息
        LoginUser loginUser = new LoginUser();
        loginUser.setUsername(dto.getMobile());
        loginUser.setPassword(dto.getPassword());
        AjaxResult result = registerFeignClient.register(loginUser);
        if (result.isSuccess()){
            //保存T_vip_user表
            Integer id =(Integer) result.getResultObj();
            VipUser vipUser = new VipUser();
            vipUser.setLoginId(Long.valueOf(id));
            vipUser.setPhone(dto.getMobile());
            vipUser.setCreateTime(System.currentTimeMillis());
            vipUser.setPassword(dto.getPassword());
            //这个状态一会要弄，三个状态：注册，激活，手机认证
            long state = BitStatesUtils.OP_REGISTED;
            state = BitStatesUtils.addState(state,BitStatesUtils.OP_ACTIVED );
            state = BitStatesUtils.addState(state,BitStatesUtils.OP_AUTHED_PHONE );
            vipUser.setBitState(state);
            vipUserMapper.insert(vipUser);
        }
        return result;
    }
}
